================================================================================
                        XENGINE GAME ENGINE DOCUMENTATION
                            Version 1.1 - 2025-2026
                  Created by Adam Kozinski & Dominik Galoch
================================================================================

TABLE OF CONTENTS
================================================================================
1. Introduction
2. System Requirements
3. Module Overview
4. XVGA256 - Graphics Module
5. XSOUND - Sound Module
6. XFONT - Font & Text Module
7. XFILES - File Management Module
8. XMOUSE - Mouse Input Module
9. XKEYBRD - Keyboard Input Module
10. XTIMER - Timer Module
11. XJOY - Joystick Module
12. Code Examples
13. Best Practices

================================================================================
1. INTRODUCTION
================================================================================

XENGINE is a comprehensive game development engine written in Turbo Pascal for
DOS systems. It provides a complete suite of tools for creating 2D games with
VGA graphics (320x200x256 colors), sound support (Sound Blaster & PC Speaker),
and multiple input devices (keyboard, mouse, joystick).

The engine is modular in design, allowing developers to use only the components
they need for their projects.

================================================================================
2. SYSTEM REQUIREMENTS
================================================================================

- IBM PC compatible computer with 286 processor or higher
- DOS operating system
- VGA graphics card (supporting mode 13h)
- Optional: Sound Blaster compatible sound card
- Optional: Mouse and/or Joystick

================================================================================
3. MODULE OVERVIEW
================================================================================

XENGINE consists of 8 main modules:

xVGA256  - Graphics rendering and image manipulation
xSound   - Audio playback (Sound Blaster and PC Speaker)
xFont    - Text rendering with customizable fonts
xFiles   - File I/O and package management
xMouse   - Mouse input handling
xKeybrd  - Keyboard input handling
xTimer   - Precise timing and delays
xJoy     - Joystick input handling

================================================================================
4. XVGA256 - GRAPHICS MODULE
================================================================================

4.1 OVERVIEW
------------
The xVGA256 module handles all graphics operations including mode switching,
bitmap loading, drawing primitives, palette management, and special effects.

4.2 CONSTANTS
-------------
SCREEN_WIDTH    = 320     - Screen width in pixels
SCREEN_HEIGHT   = 200     - Screen height in pixels
VGA_SEGMENT     = $A000   - VGA memory segment
MAX_BUFFER_SIZE = 64000   - Maximum buffer size (320x200)

4.3 DATA TYPES
--------------
TImage - Structure for bitmap images
    width   : word          - Image width in pixels
    height  : word          - Image height in pixels
    img_ptr : ^TImageBuffer - Pointer to image data
    size    : word          - Image data size

TPalette - Color palette entry
    red     : byte  - Red component (0-63)
    green   : byte  - Green component (0-63)
    blue    : byte  - Blue component (0-63)

VGAPalette - Array of 256 TPalette entries

TRectangle - Rectangular region
    x      : integer  - X coordinate
    y      : integer  - Y coordinate
    width  : integer  - Width in pixels
    height : integer  - Height in pixels

4.4 VIDEO MODE PROCEDURES
--------------------------
procedure xSetVGAMode;
    Description: Switches to VGA mode 13h (320x200x256 colors)
    Parameters: None
    Usage: Call at program start

procedure xSetTxtMode;
    Description: Returns to text mode (mode 3)
    Parameters: None
    Usage: Call before program exit

4.5 PALETTE MANAGEMENT
----------------------
procedure xSetColor(color_nr : byte; r, g, b : byte);
    Description: Sets a single palette color
    Parameters:
        color_nr - Color index (0-255)
        r, g, b  - RGB values (0-63)
    Usage: For setting individual colors

procedure xGetPaletteVGA(var pal : VGAPalette);
    Description: Reads the current VGA palette
    Parameters:
        pal - Variable to receive palette data
    Usage: For saving current palette state

procedure xSetPaletteVGA(pal : VGAPalette);
    Description: Sets the entire VGA palette
    Parameters:
        pal - Palette data to set
    Usage: For restoring or applying palettes

procedure xLoadPaletteBMP(filename : string);
    Description: Loads palette from a BMP file
    Parameters:
        filename - Path to BMP file
    Usage: For loading palettes from images

procedure xLoadBitmapPalPkg(package_name, internal_name : string);
    Description: Loads palette from a BMP file inside a package
    Parameters:
        package_name - Package file path
        internal_name - Internal file name
    Usage: For loading palettes from packaged resources

procedure xGetColor(color_nr : byte; var color : TPalette);
    Description: Gets a single palette color
    Parameters:
        color_nr - Color index (0-255)
        color    - Variable to receive color data
    Usage: For reading individual colors

procedure xSavePalFile(filename : string; var pal : VGAPalette);
    Description: Saves VGA palette to a binary file
    Parameters:
        filename - Output file path (e.g., 'MYPAL.PAL')
        pal      - Palette data to save
    Usage: For saving custom palettes to disk
    Note: Creates 768-byte file (256 colors × 3 RGB bytes)
    Example:
        var my_pal : VGAPalette;
        xGetPaletteVGA(my_pal);
        xSavePalFile('BACKUP.PAL', my_pal);

procedure xLoadPalFile(filename : string; var pal : VGAPalette);
    Description: Loads VGA palette from a binary file
    Parameters:
        filename - Input file path
        pal      - Variable to receive palette data
    Usage: For loading saved palettes from disk
    Note: Does NOT automatically set the palette in VGA
          Use xSetPaletteVGA() after loading
    Example:
        var my_pal : VGAPalette;
        xLoadPalFile('SUNSET.PAL', my_pal);
        xSetPaletteVGA(my_pal);


4.6 IMAGE LOADING & MANAGEMENT
-------------------------------
procedure xLoadBitmap(var image : TImage; filename : string);
    Description: Loads a bitmap from file
    Parameters:
        image    - TImage variable to receive data
        filename - Path to BMP file
    Usage: For loading graphics assets
    Note: Supports 8-bit (256 color) BMP files

procedure xLoadBitmapPkg(package_name, internal_name : string; 
                         var image : TImage);
    Description: Loads bitmap from package file
    Parameters:
        package_name  - Package file path
        internal_name - Internal file name
        image         - TImage variable to receive data
    Usage: For loading packaged graphics

procedure xFreeImage(var image : TImage);
    Description: Frees memory allocated for an image
    Parameters:
        image - Image to free
    Usage: Call when image is no longer needed

procedure xSaveBitmap(filename : string);
    Description: Saves current screen to BMP file
    Parameters:
        filename - Output file path
    Usage: For screenshots or saving game state

4.7 IMAGE DRAWING
-----------------
procedure xDrawBitmap(buffer_ptr : pointer; x, y : word; 
                      image : TImage; transparent : boolean);
    Description: Draws a bitmap to a buffer
    Parameters:
        buffer_ptr  - Target buffer (use nil for screen)
        x, y        - Coordinates to draw at
        image       - Image to draw
        transparent - If true, color 0 is transparent
    Usage: For rendering sprites and backgrounds

procedure xCopyImageArea(buffer_ptr : pointer; source, target : TRectangle;
                         img : TImage; transparent : boolean);
    Description: Copies a rectangular area from an image
    Parameters:
        buffer_ptr  - Target buffer
        source      - Source rectangle in image
        target      - Target rectangle on screen
        img         - Source image
        transparent - If true, color 0 is transparent
    Usage: For sprite sheets and tiled graphics

4.8 IMAGE TRANSFORMATIONS
-------------------------
procedure xScaleBitmap(original : TImage; var scaled : TImage; 
                       new_width, new_height : word);
    Description: Scales an image to new dimensions
    Parameters:
        original           - Source image
        scaled             - Output scaled image
        new_width, new_height - New dimensions
    Usage: For resizing sprites
    Note: Allocates memory for scaled image

procedure xRotateBitmap(original : TImage; var rotated : TImage; 
                        angle : real);
    Description: Rotates an image by specified angle
    Parameters:
        original - Source image
        rotated  - Output rotated image
        angle    - Rotation angle in degrees
    Usage: For sprite rotation effects
    Note: Allocates memory for rotated image

4.9 PRIMITIVE DRAWING
---------------------
procedure xDrawPixel(buffer_ptr : pointer; x, y : word; color : byte);
    Description: Draws a single pixel
    Parameters:
        buffer_ptr - Target buffer
        x, y       - Pixel coordinates
        color      - Color index
    Usage: For individual pixel manipulation

procedure xDrawLineHorz(buffer_ptr : pointer; x_start, x_end, y : word; 
                        color : byte);
    Description: Draws a horizontal line
    Parameters:
        buffer_ptr    - Target buffer
        x_start, x_end - Start and end X coordinates
        y              - Y coordinate
        color          - Color index
    Usage: For horizontal lines

procedure xDrawLineVert(buffer_ptr : pointer; x, y_start, y_end : word; 
                        color : byte);
    Description: Draws a vertical line
    Parameters:
        buffer_ptr    - Target buffer
        x             - X coordinate
        y_start, y_end - Start and end Y coordinates
        color         - Color index
    Usage: For vertical lines

procedure xDrawLineDiag(buffer_ptr : pointer; x_start, y_start, 
                        x_end, y_end : word; color : byte);
    Description: Draws a diagonal line using Bresenham algorithm
    Parameters:
        buffer_ptr       - Target buffer
        x_start, y_start - Start coordinates
        x_end, y_end     - End coordinates
        color            - Color index
    Usage: For arbitrary lines

procedure xDrawRect(buffer_ptr : pointer; x1, y1, width, height : word; 
                    color : byte; fill : boolean);
    Description: Draws a rectangle
    Parameters:
        buffer_ptr  - Target buffer
        x1, y1      - Top-left coordinates
        width, height - Dimensions
        color       - Color index
        fill        - True for filled, false for outline
    Usage: For rectangular shapes

procedure xDrawSquare(buffer_ptr : pointer; x, y, len : word; 
                      color : byte; fill_color : boolean);
    Description: Draws a square
    Parameters:
        buffer_ptr - Target buffer
        x, y       - Top-left coordinates
        len        - Side length
        color      - Color index
        fill_color - True for filled, false for outline
    Usage: For square shapes

procedure xDrawCircle(buffer_ptr : pointer; x_start, y_start, radius : word; 
                      color : byte; fill : boolean);
    Description: Draws a circle
    Parameters:
        buffer_ptr     - Target buffer
        x_start, y_start - Center coordinates
        radius         - Circle radius
        color          - Color index
        fill           - True for filled, false for outline
    Usage: For circular shapes

4.10 SPECIAL EFFECTS
--------------------
procedure xFadeOut(time : byte);
    Description: Fades the screen to black
    Parameters:
        time - Delay between fade steps (milliseconds)
    Usage: For screen transitions

procedure xFadeIn(var pal : VGAPalette; time : byte);
    Description: Fades from black to specified palette
    Parameters:
        pal  - Target palette
        time - Delay between fade steps
    Usage: For screen transitions

procedure xMeltScreen(buffer_ptr : pointer; color : byte);
    Description: Creates a "melting" screen effect
    Parameters:
        buffer_ptr - Target buffer
        color      - Fill color
    Usage: For visual effects

4.11 BUFFER MANAGEMENT
----------------------
procedure xCreateBuffer(var buffer_ptr : pointer);
    Description: Allocates memory for a double buffer
    Parameters:
        buffer_ptr - Variable to receive buffer pointer
    Usage: For double buffering (eliminates flicker)
    Note: Checks available memory before allocating

procedure xFreeBuffer(var buffer_ptr : pointer);
    Description: Frees buffer memory
    Parameters:
        buffer_ptr - Buffer to free
    Usage: Call when buffer is no longer needed

procedure xCopyBuffer(source, target : pointer);
    Description: Copies one buffer to another (optimized)
    Parameters:
        source - Source buffer
        target - Target buffer (use ptr($A000, 0) for screen)
    Usage: For page flipping in double buffering

procedure xClearScreen(buffer_ptr : pointer; color : byte);
    Description: Fills a buffer with specified color
    Parameters:
        buffer_ptr - Buffer to clear
        color      - Fill color
    Usage: For clearing screen/buffer

4.12 SYNCHRONIZATION
--------------------
procedure xWaitForVertRetrace;
    Description: Waits for vertical retrace (vsync)
    Parameters: None
    Usage: Call before screen updates to eliminate tearing

================================================================================
5. XSOUND - SOUND MODULE
================================================================================

5.1 OVERVIEW
------------
The xSound module provides audio playback capabilities for both Sound Blaster
compatible cards and the PC Speaker. It supports WAV file playback, sine wave
generation, and musical note playback.

5.2 DATA TYPES
--------------
TWavData - WAV audio data structure
    data        : Pointer  - Audio sample data
    size        : LongInt  - Data size in bytes
    sample_rate : Longint  - Sample rate (e.g., 11025 Hz)
    tc          : Byte     - Time constant for playback

TNote - Musical notes enumeration
    C, Cis, D, Dis, E, F, Fis, G, Gis, A, Ais, B

5.3 GLOBAL VARIABLES
--------------------
sb_base : Word  - Sound Blaster base port address
sb_irq  : Byte  - Sound Blaster IRQ number
sb_dma  : Byte  - Sound Blaster DMA channel

5.4 SOUND BLASTER FUNCTIONS
----------------------------
function xSBDetect: Boolean;
    Description: Detects Sound Blaster card
    Returns: True if Sound Blaster found
    Usage: Call before using Sound Blaster functions
    Note: Reads BLASTER environment variable

procedure xSBInit;
    Description: Initializes Sound Blaster
    Parameters: None
    Usage: Call after successful detection

procedure xSBDeinit;
    Description: Deinitializes Sound Blaster
    Parameters: None
    Usage: Call before program exit

procedure xSBStop;
    Description: Stops current Sound Blaster playback
    Parameters: None
    Usage: To interrupt playing sounds

5.5 SOUND PLAYBACK
------------------
procedure xLoadSound(var wav: TWavData; const file_name: string);
    Description: Loads WAV file from disk
    Parameters:
        wav       - Variable to receive WAV data
        file_name - Path to WAV file
    Usage: For loading sound effects
    Note: Supports 8-bit mono WAV files

procedure xLoadSoundPkg(package_name, internal_name: string; 
                        var wav: TWavData);
    Description: Loads WAV file from package
    Parameters:
        package_name  - Package file path
        internal_name - Internal file name
        wav           - Variable to receive WAV data
    Usage: For loading packaged sounds

procedure xPlaySound(const wav: TWavData; new_sample_rate: Longint);
    Description: Plays a loaded WAV file
    Parameters:
        wav             - WAV data to play
        new_sample_rate - Sample rate override (0 = use original)
    Usage: For playing sound effects
    Note: Changing sample rate alters pitch

procedure xPlaySine(frequency: word; duration: integer);
    Description: Generates and plays a sine wave
    Parameters:
        frequency - Frequency in Hz
        duration  - Duration in samples
    Usage: For simple sound effects

procedure xSetMasterVolume(v: Byte);
    Description: Sets Sound Blaster master volume
    Parameters:
        v - Volume level (0-255)
    Usage: For volume control

5.6 PC SPEAKER FUNCTIONS
------------------------
procedure xPlayNote(note: TNote; octave: integer; duration: word);
    Description: Plays a musical note on PC Speaker
    Parameters:
        note     - Note to play (C, D, E, etc.)
        octave   - Octave number (1-8, 4 is middle)
        duration - Duration in timer ticks
    Usage: For simple music playback
    Example: xPlayNote(A, 4, 100) plays A4 for 100 ticks

procedure xUpdateSound;
    Description: Updates PC Speaker sound state
    Parameters: None
    Usage: Call regularly in main loop when using PC Speaker

procedure xPlayPause(time : word);
    Description: Creates a pause in PC Speaker music
    Parameters:
        time - Pause duration in milliseconds
    Usage: Between notes in melodies

================================================================================
6. XFONT - FONT & TEXT MODULE
================================================================================

6.1 OVERVIEW
------------
The xFont module provides bitmap font rendering capabilities. It includes a
default 8x8 pixel font and supports loading custom fonts from bitmap files.

6.2 CONSTANTS
-------------
NUM_CHARS = 93  - Number of characters in font set

6.3 DATA TYPES
--------------
TChar - Character bitmap data (8 bytes per character)
    array[0..7] of byte

6.4 GLOBAL VARIABLES
--------------------
FONT_DATA : array[0..NUM_CHARS] of TChar  - Current font data

6.5 FONT MANAGEMENT
-------------------
procedure xInitFont;
    Description: Initializes default font
    Parameters: None
    Usage: Called automatically on unit initialization
    Note: Loads built-in 8x8 font

procedure xLoadFont(filename : string);
    Description: Loads custom font from bitmap file
    Parameters:
        filename - Path to font bitmap
    Usage: For custom fonts
    Note: Bitmap must be 8 pixels wide per character
          Characters arranged in rows

procedure xLoadFontPkg(package_name, internal_name : string);
    Description: Loads font from package file
    Parameters:
        package_name  - Package file path
        internal_name - Internal file name
    Usage: For loading packaged fonts

6.6 TEXT RENDERING
------------------
procedure xText(buffer_ptr : pointer; x, y : word; text : string; 
                color : byte);
    Description: Renders text to buffer
    Parameters:
        buffer_ptr - Target buffer
        x, y       - Text position (top-left)
        text       - Text string to render
        color      - Text color index
    Usage: For displaying text
    Note: Each character is 8x8 pixels
          Spaces are automatically handled
          Text is clipped at screen edges

6.7 SUPPORTED CHARACTERS
-------------------------
The default font supports:
- Numbers: 0-9
- Uppercase letters: A-Z
- Lowercase letters: a-z
- Special characters: . - + , / * : = _ ! @ # $ % ^ & ( ) { } [ ] ; ' " < > ? \ | ` ~
- Space character

================================================================================
7. XFILES - FILE MANAGEMENT MODULE
================================================================================

7.1 OVERVIEW
------------
The xFiles module handles file I/O operations and package file management.
It supports loading resources from both individual files and packaged archives.

7.2 DATA TYPES
--------------
THeader - Package file header
    controlNumber : integer  - Magic number (329 for valid packages)
    files         : integer  - Number of files in package

TFileInfo - File entry in package
    title  : TCharArray  - File name (64 characters max)
    size   : longint     - File size in bytes
    offset : longint     - File offset in package

7.3 FILE OPERATIONS
-------------------
function xFileExists(filename : string) : boolean;
    Description: Checks if a file exists
    Parameters:
        filename - Path to file
    Returns: True if file exists
    Usage: For checking file availability

procedure xSaveFile(const filename : string; var data; size : word);
    Description: Saves binary data to file
    Parameters:
        filename - Output file path
        data     - Data to save
        size     - Data size in bytes
    Usage: For saving game data

procedure xLoadFile(const filename : string; var data; size : word);
    Description: Loads binary data from file
    Parameters:
        filename - Input file path
        data     - Variable to receive data
        size     - Bytes to read
    Usage: For loading game data

7.4 PACKAGE FILE SYSTEM
-----------------------
procedure xOpenPakFile(const package_name, internal_name : string;
                       var fd : file; var file_size : longint; 
                       var success : boolean);
    Description: Opens a file from a package
    Parameters:
        package_name  - Package file path
        internal_name - Name of file inside package
        fd            - File handle (returned)
        file_size     - File size (returned)
        success       - Success flag (returned)
    Usage: For loading packaged resources
    Note: File remains open after call; must be closed by caller
          Used internally by other modules

7.5 PACKAGE FILE FORMAT
-----------------------
Package files have the following structure:
1. Header (THeader)
   - controlNumber = 0329 (validation)
   - files = number of files
2. File table (array of TFileInfo)
3. File data (concatenated)

To create a package:
1. Write header with control number 0329
2. Write file count
3. Write file table entries
4. Write file data in order

================================================================================
8. XMOUSE - MOUSE INPUT MODULE
================================================================================

8.1 OVERVIEW
------------
The xMouse module provides mouse input handling through the DOS mouse driver
(INT 33h). It supports position tracking, button states, and cursor customization.

8.2 GLOBAL VARIABLES
--------------------
MOUSE_LEFT   : boolean  - Left button state
MOUSE_MIDDLE : boolean  - Middle button state
MOUSE_RIGHT  : boolean  - Right button state
MOUSE_X      : word     - Mouse X position (0-319)
MOUSE_Y      : word     - Mouse Y position (0-199)

8.3 MOUSE INITIALIZATION
-------------------------
function xMouseInit : boolean;
    Description: Initializes mouse driver
    Returns: True if mouse is available
    Usage: Call at program start
    Note: Must be called before other mouse functions

8.4 CURSOR CONTROL
------------------
procedure xShowMouse;
    Description: Shows mouse cursor
    Parameters: None
    Usage: To make cursor visible

procedure xHideMouse;
    Description: Hides mouse cursor
    Parameters: None
    Usage: Before drawing to avoid cursor interference

procedure xResetMouse;
    Description: Resets mouse cursor (hide then show)
    Parameters: None
    Usage: To refresh cursor display

procedure xSetMousePosition(PosX, PosY : word);
    Description: Sets mouse cursor position
    Parameters:
        PosX - X coordinate (0-319)
        PosY - Y coordinate (0-199)
    Usage: For programmatic cursor control

8.5 MOUSE CONFIGURATION
-----------------------
procedure xSetMouseSpeed(SpeedX, SpeedY : word);
    Description: Sets mouse sensitivity
    Parameters:
        SpeedX - Horizontal sensitivity
        SpeedY - Vertical sensitivity
    Usage: For adjusting mouse response
    Note: Higher values = slower movement

procedure xSetMouseArea(MinX, MaxX, MinY, MaxY : word);
    Description: Restricts mouse movement area
    Parameters:
        MinX, MaxX - Horizontal range
        MinY, MaxY - Vertical range
    Usage: For confining cursor to specific areas

procedure xSetMouseCursor(HotX, HotY : word; Cursor : TCursor);
    Description: Sets custom cursor graphics
    Parameters:
        HotX, HotY - Cursor hotspot
        Cursor     - Cursor bitmap data
    Usage: For custom cursors

8.6 MOUSE STATE
---------------
procedure xMouseUpdate;
    Description: Updates mouse state variables
    Parameters: None
    Usage: Call in main loop to update MOUSE_X, MOUSE_Y, and button states
    Note: Must be called regularly for responsive input

================================================================================
9. XKEYBRD - KEYBOARD INPUT MODULE
================================================================================

9.1 OVERVIEW
------------
The xKeybrd module provides keyboard input handling through interrupt-based
key detection. It tracks all keys simultaneously and provides customizable
key repeat rates.

9.2 GLOBAL VARIABLES
--------------------
key          : array[1..127] of boolean  - Key state array
any_pressed  : boolean  - True if any key is pressed
key_delay    : word     - Key repeat delay
KEY_WAIT     : integer  - Key repeat counter

9.3 KEYBOARD CONSTANTS
----------------------
Scan codes for all keys are defined. Examples:
    KEY_ESC        = 1
    KEY_1 to KEY_0 = 2 to 11
    KEY_A to KEY_Z = 30, 48, 46, 32, 18, 33, 34, 35, 23, 36, 37, 38, 50, 49,
                     24, 25, 16, 19, 31, 20, 22, 47, 17, 45, 21, 44
    KEY_SPACE      = 57
    KEY_ENTER      = 28
    KEY_F1 to KEY_F12 = 59 to 68, 87, 88
    KEY_UP         = 72
    KEY_DOWN       = 80
    KEY_LEFT       = 75
    KEY_RIGHT      = 77
    (See XKEYBRD.PAS for complete list)

9.4 KEYBOARD INITIALIZATION
---------------------------
procedure xKeyboardInit;
    Description: Initializes keyboard handler
    Parameters: None
    Usage: Call at program start
    Note: Automatically restores old handler on exit

procedure xDisableKeyboard;
    Description: Restores original keyboard handler
    Parameters: None
    Usage: Called automatically on program exit

9.5 KEYBOARD FUNCTIONS
----------------------
procedure xClearKeyboard;
    Description: Clears keyboard buffer
    Parameters: None
    Usage: To discard pending keystrokes

function xKeyRetrace : boolean;
    Description: Manages key repeat rate
    Returns: True when key repeat delay expires
    Usage: For implementing key repeat
    Example:
        if key[KEY_LEFT] and xKeyRetrace then
            { Process left key }

9.6 USAGE PATTERN
-----------------
To check if a key is pressed:
    if key[KEY_SPACE] then
        { Space is pressed }

To handle key repeats:
    if key[KEY_UP] and xKeyRetrace then
        { Process up arrow with repeat rate }

To detect any key press:
    if any_pressed then
        { Some key is pressed }

To set key repeat delay:
    key_delay := 5;  { Higher = slower repeat }

9.7 CUSTOM KEYBOARD EVENTS
---------------------------
keyboard_event : TKeyboardEvent  - Custom event handler
    Set to a procedure to be called on each keyboard interrupt
    Usage:
        procedure MyKeyHandler;
        begin
            { Custom code here }
        end;
        
        keyboard_event := @MyKeyHandler;

================================================================================
10. XTIMER - TIMER MODULE
================================================================================

10.1 OVERVIEW
-------------
The xTimer module provides precise timing capabilities by reprogramming the
Programmable Interval Timer (PIT). It offers millisecond-accurate timing.

10.2 GLOBAL VARIABLES
---------------------
timer_count : longint  - Milliseconds since timer initialization
OldInt1C    : pointer  - Original timer interrupt handler

10.3 TIMER FUNCTIONS
--------------------
procedure xInitTimer(freq : word);
    Description: Initializes timer with specified frequency
    Parameters:
        freq - Timer frequency in Hz (default: 1000)
    Usage: Called automatically on unit initialization
    Note: Higher frequency = better precision, more CPU usage

function xGetTime : longint;
    Description: Returns elapsed time in milliseconds
    Returns: Milliseconds since timer initialization
    Usage: For timing measurements
    Example:
        start := xGetTime;
        { ... code ... }
        elapsed := xGetTime - start;

procedure xWait(ms : word);
    Description: Waits for specified milliseconds
    Parameters:
        ms - Milliseconds to wait
    Usage: For delays
    Note: More accurate than Delay() from CRT

procedure xRestoreTimer;
    Description: Restores original timer settings
    Parameters: None
    Usage: Call before program exit
    Note: Should be called to avoid system timing issues

10.4 TIMING PATTERNS
--------------------
Frame rate limiting:
    const FRAME_TIME = 16; { ~60 FPS }
    var frame_start : longint;
    
    repeat
        frame_start := xGetTime;
        
        { Game logic and rendering }
        
        while xGetTime - frame_start < FRAME_TIME do;
    until done;

Delta time calculation:
    var last_time, current_time, delta : longint;
    
    last_time := xGetTime;
    repeat
        current_time := xGetTime;
        delta := current_time - last_time;
        last_time := current_time;
        
        { Use delta for frame-independent movement }
        player_x := player_x + (speed * delta) div 1000;
    until done;

================================================================================
11. XJOY - JOYSTICK MODULE
================================================================================

11.1 OVERVIEW
-------------
The xJoy module provides joystick input handling for analog joysticks connected
to the game port. It supports calibration and directional input detection.

11.2 GLOBAL VARIABLES
---------------------
JOY_LEFT, JOY_RIGHT, JOY_UP, JOY_DOWN : boolean  - Direction flags
JOY_BUTTON_1, JOY_BUTTON_2            : boolean  - Button states
JOY_BUTTON_PRESSED                    : boolean  - Any button pressed flag
JOY_WAITBUTTON                        : boolean  - Button wait mode
JOY_ENABLED                           : boolean  - Joystick available flag
JOY_CALIBRATED                        : boolean  - Calibration status

Joy : TJoystick  - Joystick state structure

11.3 DATA TYPES
---------------
TJoystick - Joystick state and calibration data
    X, Y           : Word  - Current position
    XLeft, XRight  : Word  - Left/right thresholds
    YUp, YDown     : Word  - Up/down thresholds
    XCenter, YCenter : Word  - Center position
    XMin, XMax     : Word  - X axis range
    YMin, YMax     : Word  - Y axis range

11.4 JOYSTICK FUNCTIONS
-----------------------
procedure xJoyInit;
    Description: Initializes joystick
    Parameters: None
    Usage: Call at program start

procedure xJoyUpdate;
    Description: Updates joystick state
    Parameters: None
    Usage: Call in main loop
    Note: Updates position and button states

procedure xJoyReset;
    Description: Resets and centers joystick
    Parameters: None
    Usage: For initial setup
    Note: Reads center position over 16 samples

procedure xJoyCalibrate;
    Description: Calibrates joystick range
    Parameters: None
    Usage: Call while user moves joystick to extremes
    Note: Continuously updates min/max values

11.5 JOYSTICK USAGE
-------------------
Basic setup:
    xJoyInit;
    xJoyReset;
    
    { User moves joystick in full range }
    repeat
        xJoyCalibrate;
    until JOY_BUTTON_1;

Reading input:
    repeat
        xJoyUpdate;
        
        if JOY_LEFT then
            { Move left }
        if JOY_RIGHT then
            { Move right }
        if JOY_UP then
            { Move up }
        if JOY_DOWN then
            { Move down }
        if JOY_BUTTON_1 then
            { Button 1 action }
    until done;

Button wait mode:
    JOY_WAITBUTTON := true;
    repeat
        xJoyUpdate;
    until JOY_BUTTON_PRESSED;
    JOY_WAITBUTTON := false;

================================================================================
12. CODE EXAMPLES
================================================================================

12.1 BASIC PROGRAM STRUCTURE
-----------------------------
program MyGame;
uses xVGA256, xKeybrd, xMouse, xTimer;

var
    buffer : pointer;
    done   : boolean;

begin
    { Initialize }
    xSetVGAMode;
    xKeyboardInit;
    xMouseInit;
    xCreateBuffer(buffer);
    
    done := false;
    repeat
        { Input }
        xMouseUpdate;
        if key[KEY_ESC] then done := true;
        
        { Logic }
        { ... game logic ... }
        
        { Render }
        xClearScreen(buffer, 0);
        { ... draw to buffer ... }
        
        { Display }
        xWaitForVertRetrace;
        xCopyBuffer(buffer, ptr($A000, 0));
    until done;
    
    { Cleanup }
    xFreeBuffer(buffer);
    xRestoreTimer;
    xSetTxtMode;
end.

12.2 LOADING AND DISPLAYING AN IMAGE
-------------------------------------
var
    image  : TImage;
    pal    : VGAPalette;

begin
    xSetVGAMode;
    xLoadBitmap(image, 'PICTURE.BMP');
    xLoadPaletteBMP('PICTURE.BMP');
    xDrawBitmap(nil, 0, 0, image, false);
    readln;
    xFreeImage(image);
    xSetTxtMode;
end.

12.3 SPRITE WITH TRANSPARENCY
------------------------------
var
    sprite : TImage;
    x, y   : integer;

begin
    xLoadBitmap(sprite, 'SPRITE.BMP');
    
    { Draw sprite at position with transparency }
    xDrawBitmap(buffer, x, y, sprite, true);
    
    xFreeImage(sprite);
end.

12.4 SIMPLE ANIMATION
---------------------
var
    frames  : array[1..8] of TImage;
    frame   : integer;
    counter : integer;
    i       : integer;

begin
    { Load animation frames }
    for i := 1 to 8 do
        xLoadBitmap(frames[i], 'ANIM' + Chr(48 + i) + '.BMP');
    
    frame := 1;
    counter := 0;
    
    repeat
        { Animate }
        inc(counter);
        if counter >= 5 then
        begin
            counter := 0;
            inc(frame);
            if frame > 8 then frame := 1;
        end;
        
        { Draw current frame }
        xClearScreen(buffer, 0);
        xDrawBitmap(buffer, 100, 100, frames[frame], true);
        
        xWaitForVertRetrace;
        xCopyBuffer(buffer, ptr($A000, 0));
    until key[KEY_ESC];
    
    { Free frames }
    for i := 1 to 8 do
        xFreeImage(frames[i]);
end.

12.5 MOUSE-CONTROLLED MENU
---------------------------
var
    button_x, button_y : integer;
    button_w, button_h : integer;
    clicked : boolean;

begin
    button_x := 100;
    button_y := 100;
    button_w := 120;
    button_h := 30;
    
    xMouseInit;
    xShowMouse;
    
    repeat
        xMouseUpdate;
        
        { Check if mouse over button }
        if (MOUSE_X >= button_x) and (MOUSE_X <= button_x + button_w) and
           (MOUSE_Y >= button_y) and (MOUSE_Y <= button_y + button_h) then
        begin
            { Mouse over button - highlight }
            xDrawRect(buffer, button_x, button_y, button_w, button_h, 15, true);
            
            { Check for click }
            if MOUSE_LEFT then
            begin
                clicked := true;
                break;
            end;
        end
        else
        begin
            { Normal button }
            xDrawRect(buffer, button_x, button_y, button_w, button_h, 7, true);
        end;
        
        xWaitForVertRetrace;
        xCopyBuffer(buffer, ptr($A000, 0));
    until key[KEY_ESC];
end.

12.6 SOUND PLAYBACK
-------------------
var
    sound : TWavData;

begin
    if xSBDetect then
    begin
        xSBInit;
        xLoadSound(sound, 'SOUND.WAV');
        xPlaySound(sound, 0);
        
        { Wait for sound to finish }
        delay(2000);
        
        xSBDeinit;
    end;
end.

12.7 PALETTE EFFECTS
--------------------
{ Palette rotation }
var
    pal     : VGAPalette;
    temp    : TPalette;
    i       : integer;

begin
    xGetPaletteVGA(pal);
    
    repeat
        { Rotate palette colors 1-15 }
        temp := pal[1];
        for i := 1 to 14 do
            pal[i] := pal[i + 1];
        pal[15] := temp;
        
        xSetPaletteVGA(pal);
        delay(50);
    until key[KEY_ESC];
end.

12.8 TEXT DISPLAY
-----------------
var
    score : integer;
    text  : string;

begin
    score := 1234;
    
    { Display score }
    xText(buffer, 10, 10, 'SCORE:', 15);
    Str(score, text);
    xText(buffer, 70, 10, text, 14);
end.

12.9 FRAME RATE LIMITING
------------------------
const
    TARGET_FPS = 60;
    FRAME_TIME = 1000 div TARGET_FPS;

var
    frame_start : longint;

begin
    repeat
        frame_start := xGetTime;
        
        { Game logic }
        { ... }
        
        { Rendering }
        { ... }
        
        { Wait for frame time }
        while xGetTime - frame_start < FRAME_TIME do;
    until done;
end.

12.10 PACKAGE FILE USAGE
------------------------
var
    image : TImage;

begin
    { Load from package instead of individual files }
    xLoadBitmapPkg('GAME.PAK', 'TITLE.BMP', image);
    xLoadBitmapPalPkg('GAME.PAK', 'TITLE.BMP');
    
    xDrawBitmap(nil, 0, 0, image, false);
    
    xFreeImage(image);
end.

================================================================================
13. BEST PRACTICES
================================================================================

13.1 MEMORY MANAGEMENT
----------------------
- Always free images after use with xFreeImage
- Free buffers before program exit with xFreeBuffer
- Check available memory before large allocations
- Use packages to reduce memory fragmentation

13.2 GRAPHICS
-------------
- Use double buffering to eliminate flicker:
  * Draw to buffer
  * Wait for vertical retrace
  * Copy buffer to screen
- Hide mouse cursor before drawing (xHideMouse)
- Use transparency for sprites (color 0 = transparent)
- Clip coordinates to screen bounds manually when needed
- Use xWaitForVertRetrace before screen updates

13.3 INPUT
----------
- Call update functions in main loop:
  * xMouseUpdate for mouse
  * xJoyUpdate for joystick
  * (Keyboard updates automatically via interrupt)
- Use xKeyRetrace for proper key repeat handling
- Initialize all input devices at program start
- Restore handlers before exit (automatically done)

13.4 SOUND
----------
- Detect Sound Blaster before use (xSBDetect)
- Deinitialize Sound Blaster on exit (xSBDeinit)
- Use PC Speaker as fallback if no Sound Blaster
- Load frequently used sounds once, reuse
- Free sound data when no longer needed

13.5 TIMING
-----------
- Use xTimer for accurate timing, not CRT.Delay
- Restore timer before exit (xRestoreTimer)
- Implement frame rate limiting
- Use delta time for smooth animation

13.6 FILE OPERATIONS
--------------------
- Use packages for commercial distribution
- Check file existence before loading
- Handle file errors gracefully
- Close files after use
- Use consistent path separators

13.7 OPTIMIZATION
-----------------
- Minimize palette changes (expensive operation)
- Use clipping to avoid drawing off-screen
- Clear only necessary screen areas
- Batch similar drawing operations
- Use assembly routines for critical code
- Pre-calculate values outside loops

13.8 DEBUGGING
--------------
- Use xSetTxtMode before writeln for debugging
- Initialize all variables
- Check return values from detection functions
- Implement graceful error handling

13.9 COMPATIBILITY
------------------
- Test on various DOS systems
- Provide PC Speaker fallback
- Handle missing mouse/joystick gracefully
- Support different VGA cards
- Document system requirements

13.10 CODE ORGANIZATION
-----------------------
- Separate game logic from rendering
- Use constants for magic numbers
- Comment complex algorithms
- Create reusable procedures
- Keep procedures focused and small

================================================================================
END OF DOCUMENTATION
================================================================================
Official Website: http://xengine.hhdns.pl

For support or bug reports, contact e-mail:
xengine@hhdns.pl 
domino.67h@gmail.com

This documentation covers XENGINE version 1.1

Changes in version 1.1:
- Added xSavePalFile and xLoadPalFile procedures for palette file management